<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Controller for Shift related stuff
 *
 * @category    RedCross
 * @package     Core_Controller
 */
class Core_CalendarController extends Zend_Controller_Action
{

	const PARAMETER_DATE_FORMAT = 'YYYYMM';
	
    private $_memberService;
    private $_passiveService;
    private $_shiftService;
	
    public function init()
    {
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
        $this->_passiveService = $this->_helper->getService('Core_Service_Passive');
        $this->_shiftService = $this->_helper->getService('Core_Service_Shift');
    }

    public function indexAction()
    {
        $this->_helper->acl()->isAllowed('action:core.calendar', 'all');

    	$member_id = $this->view->authInfo()->getMemberId();
        $this->view->memberId = $member_id;

    	$addMessageForm = new Core_Form_Passive_Add();

        $newtimecode = null;
        $msg = '';

		$request = $this->getRequest();
		if ($request->isPost() && $addMessageForm->isValid($request->getPost())) {
            $postData = $addMessageForm->getValues();
			$postData['member_id'] = $member_id;

			$result = $this->_memberService->addPassiveMessage($postData);
			if ($result === Core_Service_Member::INVALID_PASSIVE_START_DATE) {
				$msg = $this->view->flashMessage()->renderMessage('Ugyldig startdato valgt', RedCross_View_Helper_FlashMessage::ERROR);
			}
			else if ($result === Core_Service_Member::INVALID_PASSIVE_END_DATE){
				$msg = $this->view->flashMessage()->renderMessage('Ugyldig sluttdato valgt', RedCross_View_Helper_FlashMessage::ERROR);
			}
			else if ($result === true) {
                $msg = $this->view->flashMessage()->renderMessage('Passivmelding lagt til', RedCross_View_Helper_FlashMessage::SUCCESS);

                $date = $request->getParam('from_date');
				$newtimecode = substr($date, 6, 4) . substr($date, 3, 2);
				$this->view->calendar = $this->_createCalendar($member_id, $newtimecode);
			}
			else {
				$msg = $this->view->flashMessage()->renderMessage('En feil oppstod under innleggelse', RedCross_View_Helper_FlashMessage::ERROR);
			}	
		}
        $this->view->flashMessage = $msg;
		
		if($newtimecode == null) {
			$timecode = $this->_getParam('date');
		} else {
			$timecode = $newtimecode;
		}
		$this->view->calendar = $this->_createCalendar($member_id, $timecode);
		
    	$addMessageForm->fillForm(array('member_id' => $member_id));
    	$this->view->addMessageForm = $addMessageForm;
    }
    
    public function addpassivedayAction()
    {
        $this->_helper->acl()->isAllowed('action:core.calendar', 'all');

        $this->_helper->viewRenderer->setNoRender(true);

        $authService = $this->_helper->authenticator();
        $memberId = $authService->getIdentity()->member_id;

        $date = $this->_getParam('date'); //2010-05-13 00:00:00

        $passiveMessage = new Core_Model_Passive();
        $passiveMessage->date = $date;
        $passiveMessage->member_id = $memberId;

        if($this->_passiveService->save($passiveMessage)){
            $this->view->flashMessage()->addMessage('Passivmelding lagt til.',RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('En feil oppstod under innleggelse.' ,RedCross_View_Helper_FlashMessage::ERROR);
        }

        $redirectDate .= substr($date, 0, 4) . substr($date, 5, 2);
        return $this->_helper->redirector('index', null, null, array('date' => $redirectDate));
    }
    
    public function removeMessageAction()
    {
        $this->_helper->acl()->isAllowed('action:core.calendar', 'all');

    	$this->_helper->viewRenderer->setNoRender(true);
    	$message_id = $this->_getParam('id');
		$dateParam = $this->_getParam('date');
        
    	$validator = new Zend_Validate_Int();
        if (!$validator->isValid($message_id))
        {
            throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
        }
        $message_id = (int)$message_id;

        $message = $this->_passiveService->fetch($message_id);
        if (!is_object($message))
        {
        	throw new RedCross_Exception_NotFound('Angitt passivmelding ikke funnet');
        }
        
        if($this->_passiveService->delete($message) == 1){
            $this->view->flashMessage()->addMessage('Passivmelding fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('Klarte ikke å fjerne passivmelding', RedCross_View_Helper_FlashMessage::ERROR);
        }


        return $this->_helper->redirector('index', null, null, array('date' => $dateParam));
    }

    private function _createCalendar($member_id, $timecode = null)
    {
		$date = new RedCross_Date();

       	$date->setDay(1);
        $date->setHour(0);
        $date->setMinute(0);
        $date->setSecond(0);

    	if (!is_null($timecode) && !empty($timecode) && Zend_Date::isDate($timecode, self::PARAMETER_DATE_FORMAT)) {
            $year = substr($timecode, 0, 4);
            $month = substr($timecode, 4, 2);
            $date->setYear($year);
            $date->setMonth($month);
    	}
        
    	$calendar = new Core_Model_Calendar($date);
    	
    	$anotherDate = new Redcross_Date($date);
    	$from_date = $anotherDate->export();
    	$anotherDate->add(1, Zend_Date::MONTH);
    	$to_date = $anotherDate->export();
    	
    	$passiveMessages = $this->_memberService->getPassiveMessages($member_id, $from_date, $to_date);
    	$calendar->setPassiveMessages($passiveMessages);
    	
    	$shifts = $this->_shiftService->fetchAllVisibleForMember($member_id, array('from_date' => $from_date, 'to_date' => $to_date));
    	$calendar->setShifts($shifts);
    	
		return $calendar;    	
    }
    
}
